<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../../../../static/lib/layuiadmin/layui/css/layui.css" media="all">
</head>
<body>

<table class="layui-hide" id="demo" lay-filter="test3"></table>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="delRow"><i class="layui-icon layui-icon-delete"></i>删除行</a>
</script>

<script type="text/javascript" src="../../../common/layuiInit.js"></script>

<script>
    var $ = layui.$
    var table = layui.table
    //建立全局对象 tableData，在数据操作时同步数据到对象中
    var tableData = [{
        "id": "10001"
        ,"username": "杜甫"
        ,"email": "xianxin@layui.com"
        ,"sex": "男"
        ,"city": "浙江杭州"
        ,"sign": "人生恰似一场修行"
    }]

    //动态生成标题栏
    var colData = [[
        {field: 'id', title: 'ID', width: 80, edit: 'text'}
        ,{field: 'username', title: '用户名', width: 120, edit: 'text'}
        ,{field: 'email', title: '邮箱', minWidth: 150, edit: 'text'}
        ,{field: 'sign', title: '签名', minWidth: 160, edit: 'text'}
        ,{field: 'sex', title: '性别', width: 80, edit: 'text'}
        ,{field: 'city', title: '城市', width: 100, edit: 'text'}
        ,{field: 'operTool', title: '操作', width: 180, toolbar: '#barDemo'}
    ]]

    table.render({
        elem: '#demo'
        ,cols: colData
        ,data: tableData
        ,done: function(res, curr, count){
            $("[data-field='operTool']").children().each(function (index) {
                if($.trim($(this).text())=="操作") {
                    $(this).html('<a class="layui-btn layui-btn-normal layui-btn-xs" onclick="newRow()"><i class="layui-icon layui-icon-add-1"></i>新增行</a>')
                }
            })
        }
    });

    //监听单元格编辑
    table.on('edit(test3)', function(obj){
        var value = obj.value //得到修改后的值
        var field = obj.field; //得到字段
        //修改单元格，对应操作tableData
        tableData[getRowIndex(obj)][field] = value
    });

    //监听按钮事件
    table.on('tool(test3)', function(obj){
        // console.log(obj.event)

        if(obj.event === 'delRow'){
            layer.confirm('确定删除行？', function(index){
                //操作数据
                tableData.splice(getRowIndex(obj), 1)
                //刷新表格
                table.reload('demo', {data:tableData})
                layer.close(index);
            });
        }
    });


    function getRowIndex(obj) {
        var resIndex = -1
        var indexOfTableData = (obj.tr.selector).match(/"(\d+)"]$/)
        if (indexOfTableData) resIndex = parseInt(indexOfTableData[1])

        return resIndex
    }

    function newRow() {
        //操作数据
        tableData.push({})
        //刷新表格
        table.reload('demo', {data:tableData})
    }
</script>

</body>
</html>